const express = require('express');
const fs = require('fs');
const path = require('path');
const app = express();
const port = 3000;

// 解析 JSON 请求体
app.use(express.json());

// 静态文件服务
app.use(express.static(path.join(__dirname, 'public')));

// 自动加载 routes 目录下的所有路由模块，并收集路由信息
const loadRoutes = () => {
    const routesDir = path.join(__dirname, 'routes');
    const routePaths = [];

    fs.readdirSync(routesDir)
        .filter(file => file.endsWith('.js'))
        .forEach(file => {
            const routePath = path.join(routesDir, file);
            const routeModule = require(routePath);

            // 假设每个路由模块都导出了一个 express.Router 实例
            const routerName = path.basename(file, '.js');
            const basePath = `/api/${routerName.replace('Routes', '')}`;

            app.use(basePath, routeModule);
            console.log(`已加载路由: ${basePath} (来自 ${file})`);

            // 收集路由信息用于首页展示
            const routes = extractRoutes(routeModule, basePath);
            routePaths.push(...routes);
        });

    return routePaths;
};

// 提取路由信息（方法、路径、描述等）
const extractRoutes = (router, basePath) => {
    const routes = [];
    const stack = router.stack || [];

    stack.forEach(layer => {
        if (layer.route) {
            const route = layer.route;
            const methods = Object.keys(route.methods).map(m => m.toUpperCase());
            const path = basePath + route.path;

            // 尝试从路由处理函数中提取描述信息（如果有）
            const handler = route.stack[0].handle;
            const description = handler.description || '';
            const parameters = handler.parameters || [];

            // 确定分组（从路径中提取）
            const group = path.split('/')[2] || '其他';

            methods.forEach(method => {
                routes.push({
                    method,
                    path,
                    description,
                    group: group.charAt(0).toUpperCase() + group.slice(1),
                    file: handler.filename || '未知',
                    parameters
                });
            });
        }
    });

    return routes;
};

// 加载所有路由并获取路由信息
const routes = loadRoutes();

// 首页路由
app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

// API 文档路由
app.get('/api/docs', (req, res) => {
    res.json({
        code: 200,
        message: '获取 API 文档成功',
        data: routes
    });
});

// 启动服务
app.listen(port, () => {
    console.log(`Mock 服务已启动，访问地址：http://localhost:${port}`);
});  